<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\facade\Session;
use think\Request;
use think\facade\View;
use think\exception\ValidateException;

use app\admin\validate\RoleValidate;
use app\admin\validate\MenuValidate;
use app\admin\validate\AdminValidate;

use app\admin\model\Admin;
use app\admin\model\Menu;
use app\admin\model\Role;

class AuthController extends BaseController
{
    // 管理员列表页面
    public function admin_list()
    {   
        return view();
    }

    // 渲染管理员添加页面
    public function admin_add()
    {   
        $adminModel = new Admin();
        $admin_list = $adminModel->getList([['role_id', '<', 2], ['del_time', '=', 0]], 0);

        View::assign('admin_list', $admin_list['data']);
        return view();
    }

    // 渲染管理员编辑页面
    public function admin_edit()
    {   
        $data = input('get.');
        $adminModel = new Admin();

        $adminInfo = $adminModel->getFind(['id' => $data['id']])['data'];
        $regionArr = explode('-', $adminInfo['region']);

        $adminInfo['province'] = $regionArr[0];
        $adminInfo['city']     = $regionArr[1];
        $adminInfo['area']     = $regionArr[2];

        $admin_list = $adminModel->getList([['role_id', '=', $adminInfo->getData('role_id') - 1], ['del_time', '=', 0]], 0);

        View::assign('admin_list', $admin_list['data']);
        View::assign('admin', $adminInfo);
        return view();
    }

    // 获取管理员列表
    public function admin_data()
    {   
        $adminModel = new Admin();
        $data = input('get.');

        // 验证数据
        try{
            validate(AdminValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['del_time', '=', 0];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $count = $adminModel->getNum($where)['data'];

        $field = 'id, username, nickname, region, address, is_business, role_id, status';
        $list = $adminModel->getList($where, 1, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 管理员的启用||禁用
    public function setStatus()
    {
        $id = input('post.id');
        $adminModel = new Admin();
        $status = $adminModel->setStatus($id);

        $this->success_back($status['msg']);
    }

    // 管理员添加
    public function adminAdd()
    {   
        $adminModel = new Admin();
        $data = input('post.');

        // 验证数据
        try{
            validate(AdminValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        /** 查询待注册账号是否已存在 */
        $admin_info = $adminModel->getFind(['username' => $data['username']], 'id');

        if($admin_info['code'] == 'ok'){
            $this->error_back('该账号已存在');
        }

        /** 查询上级的角色 */
        $admin_up_info = $adminModel->getFind(['id' => $data['pid']], 'role_id');

        if($admin_up_info['data']->getData('role_id') == 0){
            $data['role_id'] = 1;
        }else if($admin_up_info['data']->getData('role_id') == 1){
            $data['role_id'] = 2;
        }else{
            $this->error_back('角色信息错误');
        }

        $data['region'] = $data['province'] . '-' . $data['city'] . '-' . $data['area'];

        if($data['city'] == '市辖区'){
            $data['city'] = $data['province'];
        }

        $data['password'] = setPass($data['password']);
        $flag = $adminModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    // 管理员信息修改
    public function setAdminEdit()
    {   
        $adminModel = new Admin();
        $data = input('post.');

        // 验证数据
        try{
            validate(AdminValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $username_num = $adminModel->getNum(['username' => $data['username']]);

        if($username_num['data'] > 1){
            $this->error_back('该账号已存在');
        }

        if(empty($data['password'])){
            unset($data['password']);
        }else{
            $data['password'] = setPass($data['password']);
        }
        
        $data['region'] = $data['province'] . '-' . $data['city'] . '-' . $data['area'];
        $flag = $adminModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('修改成功');
    }

    // 删除管理员
    public function adminDel()
    {
        $adminModel = new Admin();
        $data = input('post.');

        // 验证数据
        try{
            validate(AdminValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $adminModel->edit(['id' => $data['id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }





    // 渲染角色列表页面
    public function role_list()
    {   
        return view();
    }

    // 渲染角色添加页面
    public function role_add()
    {   
        $menuModel = new Menu();

        $menuList = $menuModel->getList([['pid', '<>', 0]], 0);

        View::assign('menu', $menuList['data']);
        return view();
    }

    // 渲染角色编辑页面
    public function role_edit()
    {   
        $data = input('get.');
        $roleModel = new Role();
        $menuModel = new Menu();

        $roleInfo = $roleModel->getFind(['id' => $data['id']])['data'];

        $roleInfo['menu_arr'] = explode(',', $roleInfo->getData('menu'));
        $roleInfo = $roleInfo->toArray();
        array_pop($roleInfo['menu_arr']);

        $menuList = $menuModel->getList([['pid', '<>', 0]], 0);

        View::assign('role', $roleInfo);
        View::assign('menu_list', $menuList['data']);
        return view();
    }

    // 获取角色列表
    public function role_data()
    {   
        $roleModel = new Role();
        $data = input('get.');

        // 验证数据
        try{
            validate(RoleValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['id', '>', 1];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $count = $roleModel->getNum($where)['data'];

        $field = 'id, name, menu';
        $list = $roleModel->getList($where, 1, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 角色添加
    public function roleAdd()
    {   
        $roleModel = new Role();
        $data = input('post.');

        // 验证数据
        try{
            validate(RoleValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $roleModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    // 角色信息修改
    public function setRoleEdit()
    {   
        $roleModel = new Role();
        $data = input('post.');

        // 验证数据
        try{
            validate(RoleValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $flag = $roleModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('修改成功');
    }

    // 删除角色
    public function roleDel()
    {
        $roleModel = new Role();
        $data = input('post.');

        // 验证数据
        try{
            validate(RoleValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $roleModel->del(['id' => $data['id']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }







    // 渲染权限列表页面
    public function menu_list()
    {   
        return view();
    }

    // 渲染权限添加页面
    public function menu_add()
    {   
        $menuModel = new Menu();

        $menuList = $menuModel->getList(['pid' => 0], 0);

        View::assign('menu', $menuList['data']);
        return view();
    }

    // 渲染图标页面
    public function icon()
    {
        return view();
    }

    // 渲染权限编辑页面
    public function menu_edit()
    {   
        $data = input('get.');
        $menuModel = new Menu();

        $menuInfo = $menuModel->getFind(['id' => $data['id']])['data'];
        $menuList = $menuModel->getList([['pid', '=', 0], ['id', '<>', $menuInfo->getData('pid')]])['data'];

        View::assign('menu', $menuInfo);
        View::assign('menu_list', $menuList);
        return view();
    }

    // 获取权限列表
    public function menu_data()
    {   
        $menuModel = new Menu();
        $data = input('get.');

        $where = [];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $count = $menuModel->getNum($where)['data'];

        $field = 'id, name, icon, sort, rule, is_show';
        $list = $menuModel->getList($where, 1, $data['page'], $data['limit'], $field, 'sort DESC,id');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        foreach($list['data'] as $k => $v){
            $list['data'][$k]['rule_url'] = $v->getData('rule');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 权限添加
    public function menuAdd()
    {   
        $menuModel = new Menu();
        $data = input('post.');

        // 验证数据
        try{
            validate(MenuValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $menuModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    // 权限信息修改(单元格修改)
    public function setMenuOnlyEdit()
    {   
        $menuModel = new Menu();
        $data = input('post.');
        $editArr = ['id' => $data['id'], $data['field'] => $data['value']];

        // 验证数据
        try{
            validate(MenuValidate::class)->scene('editSort')->check($editArr);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $flag = $menuModel->edit($editArr);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('修改成功');
    }

    // 权限信息修改
    public function setMenuEdit()
    {   
        $menuModel = new Menu();
        $data = input('post.');

        // 验证数据
        try{
            validate(MenuValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $menuModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('修改成功');
    }

    // 删除权限
    public function menuDel()
    {
        $menuModel = new Menu();
        $data = input('post.');

        // 验证数据
        try{
            validate(MenuValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $menuModel->del(['id' => $data['id']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }
}
